package org.dashboard.server.serversup;

import org.dashboard.client.widget.serversup.ServersUpService;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.dashboard.shared.Props;
import org.dashboard.shared.serversup.ServerInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class ServersUpServiceImpl extends RemoteServiceServlet implements ServersUpService {

    ArrayList<ServerInfo> result = new ArrayList<ServerInfo>();

    public ServersUpServiceImpl() {
        Props props = Props.instance();
        String[] urls = props.getServersUpConfig().get(2);
        for (String url : urls) {
            result.add(new ServerInfo(null, url));
        }
    }

    public ArrayList<ServerInfo> getStates() throws IllegalArgumentException {
        for (ServerInfo serverInfo : result) {
            serverInfo.setAlive(getBuildInfoFile(serverInfo) != null);
        }
      return result;
  }

    private String getBuildInfoFile(ServerInfo serverInfo) {
        BufferedReader br = null;
        try {
            URL url = new URL(serverInfo.getServerURL());
            br = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuilder builder = new StringBuilder();
            String inputLine;
            while ((inputLine = br.readLine()) != null) {
                builder.append(inputLine);
            }
            return builder.toString();
        } catch (Exception ex) {
            Logger.getLogger(getClass().getName()).log(Level.INFO, serverInfo.getName() +" is down!");
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(getClass().getName()).log(Level.INFO, serverInfo.getName() +" failed!");
            }
        }
        return null;
    }
}
